package com.fileServer.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

/**
 * @author 大忽悠
 * @create 2023/2/13 14:41
 */
@Slf4j
public class FileUtil {
    /**
     * UUID替换原来的文件名
     */
    public static String generatorFileName(String fileName) {
        return UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
    }

    public static String getFileUrl(String ... paths) {
        return String.join("/", paths);
    }

    public static void createDir(String rootPath, String bucketName) {
        try {
            Files.createDirectory(Path.of(rootPath, bucketName));
        } catch (IOException e) {
            log.error("创建目录过程中出现错误: ", e);
        }
    }

    public static void createDir(String dirPath){
        File file = new File(dirPath);
        if(!file.exists()){
            file.mkdirs();
        }
    }

    public static String pathMerge(String rootPath, String bucketName, String objectName) {
        if (objectName.startsWith("/") || objectName.startsWith("\\")) {
            objectName = objectName.substring(1);
        }
        return String.join(File.separator,rootPath, bucketName, objectName);
    }

    public static void transFileTo(InputStream stream, String filePath) throws IOException {
        File file = new File(filePath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(stream);
             PrintStream printStream = new PrintStream(filePath)) {
            byte[] data = new byte[1024];
            int len = -1;
            while ((len = bufferedInputStream.read(data)) != -1) {
                printStream.write(data, 0, len);
            }
            printStream.flush();
        }
    }

    public static void deleteFile(String filePathOrDirPath) {
        try{
            cn.hutool.core.io.FileUtil.del(filePathOrDirPath);
        }catch (RuntimeException e){
             log.error("文件删除过程中出现异常,文件名为: {} ,异常信息为: ",filePathOrDirPath,e);
        }
    }
}
